package com.pomelo.chat.service.impl;

import com.alibaba.fastjson.JSON;
import com.pomelo.chat.config.ChatConfig;
import com.pomelo.chat.config.ChatGPTConfig;
import com.pomelo.chat.domain.Chat;
import com.pomelo.chat.service.ChatGPTService;
import com.pomelo.chat.service.ChatService;
import com.pomelo.chat.util.ChatResult;
import com.pomelo.chat.util.Question;
import com.theokanning.openai.OpenAiService;
import com.theokanning.openai.completion.CompletionChoice;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.completion.CompletionResult;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class ChatGPTServiceImpl implements ChatGPTService {

    private static final Logger logger = LoggerFactory.getLogger(ChatGPTServiceImpl.class);

    @Resource
    private ChatConfig chatConfig;
    private OpenAiService openAiService;
    private ChatGPTConfig chatGPTConfig;

    @Resource
    private ChatService chatService;

    @Override
    public Chat askGPT3(Question question, HttpServletRequest request) {
        if (openAiService == null) {
            openAiService = new OpenAiService(chatConfig.getToken(), chatConfig.getTimeOut());
            chatGPTConfig = chatConfig.getChatGPT();
        }
        return ask(question, request);
    }

    private Chat ask(Question question, HttpServletRequest request) {
        CompletionRequest completionRequest = CompletionRequest.builder()
                .prompt(question.getQ())
                .model(chatGPTConfig.getModel())
                .temperature(chatGPTConfig.getTemperature())
                .maxTokens(chatGPTConfig.getMaxTokens())
                .topP(chatGPTConfig.getTopP())
                .echo(chatGPTConfig.getEcho())
                .build();
        CompletionResult result = openAiService.createCompletion(completionRequest);
        List<CompletionChoice> choices = result.getChoices();
        CompletionChoice choice = choices.get(0);
        Chat chat = new Chat();
        chat.setUsername("GaoYang");
        chat.setUserKey(result.getId());
        chat.setModel(result.getModel());
        chat.setPrompt(question.getQ());
        chat.setAnswer(choice.getText());
        chat.setIsEnd("stop".equals(choice.getFinish_reason()));
        chat.setIpAddress(request.getRemoteAddr());
        chat.setResponseJson(choice.toString());
        chat.setPromptId(result.getId());
        chat.setFinishReason(choice.getFinish_reason());
        chat.setQuestUrl(null);
        int insert = chatService.insert(chat);
        if (insert < 0) {
            logger.error("插入数据库失败！");
        } else {
            logger.info("插入数据成功！");
        }
        return chat;
    }
}
